package com.fenye.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class JdbcUtil {
	private Connection util(){
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8";
			conn = DriverManager.getConnection(url,"root","123456");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	public int executeUpt(String sql,Object[] obj){
		Connection  con = this.util();
		int k=0;
		PreparedStatement pst = null;
		try {
			 pst = con.prepareStatement(sql);
			if(obj != null){
				for(int i=0;i<obj.length;i++){
					pst.setObject(i+1, obj[i]);
				}
			}
			k = pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				pst.close();
				con.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return k;
 	}
	
	public List<Map<String,String>> executeSel(String sql,Object[] obj){
		Connection  con = this.util();
		PreparedStatement pst = null;
		List<Map<String,String>> list = null;
		ResultSet rs = null;
		try {
			 pst = con.prepareStatement(sql);
			if(obj != null){
				for(int i=0;i<obj.length;i++){
					pst.setObject(i+1, obj[i]);
				}
			}
			rs = pst.executeQuery();
			ResultSetMetaData rmd =rs.getMetaData();
			list = new ArrayList<Map<String,String>>();
			Map<String,String> ma = new HashMap();
			if(rmd != null){
				for(int i =1;i<rmd.getColumnCount();i++){
					ma.put(rmd.getColumnName(i), rs.getString(i));
				}
				list.add(ma);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				pst.close();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return list;
	}
}
